package com.megvii.koala.guard;

import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by linyue on 16/1/8.
 */
public class BoxManager
{
    private static final String LOG_TAG = "BoxManager";

    private static final long PERIOD = 10 * 60 * 1000;

    private static final long VALIDATE_MIN_INTERVAL = 10 * 1000;

    private List<Box> boxes;

    private Runnable validateTask;

    private ExecutorService executorService;

    private TimerTask timerTask;

    private Timer timer;

    private boolean validating = false;

    private long lastValidateTime = 0;

    private boolean inited = false;

    public BoxManager()
    {
        super();
        boxes = new ArrayList<>();
    }

    public void init()
    {
        synchronized (this)
        {
            Log.d(LOG_TAG, "BoxManager init");
            if (inited)
            {
                return;
            }
            inited = true;
            executorService = Executors.newFixedThreadPool(1);
            validateTask = new ConcurrentValidateTask();
            timerTask = new TimerTask()
            {
                @Override
                public void run()
                {
                    validate();
                }
            };
            timer = new Timer();
            timer.schedule(timerTask, PERIOD, PERIOD);
        }
    }

    public void release()
    {
        synchronized (this)
        {
            Log.d(LOG_TAG, "BoxManager release");
            if (executorService != null)
            {
                executorService.shutdownNow();
            }
            if (timer != null)
            {
                timer.cancel();
            }
            inited = false;
        }
    }

    public void validate()
    {
        Log.d(LOG_TAG, "BoxManager validate");
        synchronized (this)
        {
            if (validating || System.currentTimeMillis() - lastValidateTime < VALIDATE_MIN_INTERVAL)
            {
                return;
            }
            validating = true;
            lastValidateTime = System.currentTimeMillis();
            executorService.submit(validateTask);
        }
    }

    public List<Box> getValidBoxes()
    {
        List<Box> result = new ArrayList<>();
        synchronized (this)
        {
            for (Box box : boxes)
            {
                if (box.valid)
                {
                    result.add(box);
                }
            }
        }
        return result;
    }

    public Box getRandomValidBox()
    {
        List<Box> validBoxes = getValidBoxes();
        if (validBoxes.isEmpty())
        {
            return null;
        }
        int randomIndex = (int) (Math.random() * validBoxes.size());
        return validBoxes.get(randomIndex);
    }

    public Box getFirstValidBox()
    {
        List<Box> validBoxes = getValidBoxes();
        if (validBoxes.isEmpty())
        {
            return null;
        }
        return validBoxes.get(0);
    }

    public List<Box> getInvalidBoxes()
    {
        List<Box> result = new ArrayList<>();
        synchronized (this)
        {
            for (Box box : boxes)
            {
                if (!box.valid)
                {
                    result.add(box);
                }
            }
        }
        return result;
    }

    public List<Box> getAllBoxes()
    {
        List<Box> result = new ArrayList<>();
        synchronized (this)
        {
            result.addAll(boxes);
        }
        return result;
    }

    public void addBox(Box box)
    {
        Log.d(LOG_TAG, "BoxManager add box " + box.address);
        synchronized (this)
        {
            boxes.add(box);
        }
    }

    void setBoxValid(int id, boolean valid)
    {
        Log.d(LOG_TAG, "BoxManager set box valid " + valid + " " + id);
        synchronized (this)
        {
            for (Box box : boxes)
            {
                if (box.id == id)
                {
                    box.valid = valid;
                }
            }
        }
    }

    public void clear()
    {
        Log.d(LOG_TAG, "BoxManager release");
        synchronized (this)
        {
            boxes.clear();
        }
    }

    public class ConcurrentValidateTask implements Runnable, BoxValidator.BoxValidatorListener
    {
        public void run()
        {
            Log.d(LOG_TAG, "validation task start");
            List<Box> boxes = getAllBoxes();
            for (Box box : boxes)
            {
                BoxUDPValidator validator = new BoxUDPValidator();
                validator.setListener(this);
                Log.d(LOG_TAG, "validating {" + box.id + ", " + box.address + "}");
                validator.validate(box.id, box.address);
            }
            validating = false;
            Log.d(LOG_TAG, "validation task completed");
        }

        @Override
        public void onValidateResult(int id, boolean valid)
        {
            Log.d(LOG_TAG, "validate result {" + id + ", " + valid + "}");
            setBoxValid(id, valid);
        }
    }
}
